// ignore_for_file: use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/ticket_list_model.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/routers/jump_router.dart';
import 'package:tiktokadult/tools_base/debug_log.dart';
import 'package:tiktokadult/tools_base/loading/loading_alert_widget.dart';
import 'package:tiktokadult/tools_base/net/base_resp_bean.dart';

import '../../hj_model/acg/comic_chapters_model.dart';
import '../../hj_model/cartoon_media_info.dart';
import '../../hj_model/media_content.dart';
import '../../hj_model/user/wallet_model_entity.dart';
import '../../hj_model/video_model.dart';
import '../../hj_utils/api_service/mine_service.dart';
import '../../hj_utils/global.dart';
import '../../tools_base/global_store/store.dart';
import '../../tools_base/net/api_exception.dart';

///购买漫画弹窗
class VideoCartoonBuyAlert extends StatefulWidget {
  final VideoModel? videoModel; //视频，动漫视频
  final ComicChapterInfo? curModel; // 单节

  const VideoCartoonBuyAlert({
    this.videoModel,
    super.key,
    this.curModel,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoCartoonBuyAlertState();
  }
}

class _VideoCartoonBuyAlertState extends State<VideoCartoonBuyAlert> {
  bool isBuying = false;
  bool isMoneyEnough = true; // 余额不足

  VideoModel? get videoModel => widget.videoModel;

  CartoonMediaInfo? get mediaInfo => widget.videoModel?.mediaInfo; //动漫

  MediaContent? get mediaSubInfo {
    // 动漫子集数据
    return widget.curModel?.mediaContent;
  }

  WalletModelEntity? get wallet => globalStore.getWallet();

  bool get isVip => globalStore.isVIP();

  bool get isHasCoupon {
    return discountArr.isNotEmpty;
  }

  int get discountPrice {
    return (videoModel?.mediaInfo?.price ?? mediaInfo?.price ?? 0) - (videoModel?.subPrice ?? mediaSubInfo?.price ?? 0);
  }

  String get priceTitle {
    return "${videoModel?.subPrice ?? mediaSubInfo?.price ?? widget.curModel?.price}金币";
  }

  List<TicketModel> discountArr = [];
  TicketModel? selectEntity;

  @override
  void initState() {
    super.initState();
    globalStore.refreshWallet().then((value) {
      if (mounted) {
        isMoneyEnough = (wallet?.amount ?? 0) >= (videoModel?.subPrice ?? mediaSubInfo?.price ?? 0);
        setState(() {});
      }
    });
  }

  ///购买作品
  _buyProduct(bool isAll) async {
    if (isMoneyEnough == false) {
      await jumpToWalletPage(tabPosition: 1);
      isMoneyEnough = true;
      setState(() {});
      return;
    }
    if (isBuying) return;
    isBuying = true;
    setState(() {});
    try {
      int productType = 19; //  19 购买整本，25 购买子集
      String? productID = videoModel?.id ?? mediaInfo?.id ?? widget.curModel?.mediaId;
      if (!isAll) {
        productType = 25;
        productID = videoModel?.subid ?? mediaSubInfo?.id ?? widget.curModel?.id;
      }

      LoadingAlertWidget.show();
      BaseRespBean data = await MineService.postBuyVideo(productID, productType);
      LoadingAlertWidget.cancel();
      if (data.isSuccess) {
        videoModel?.vidStatus?.hasPaid = true;
        mediaSubInfo?.mediaStatus?.hasPaid = true;
        widget.curModel?.hasBuy = true;
        if (isAll) {
          mediaInfo?.mediaStatus?.hasPaid = true;
          for (MediaContent item in (videoModel?.mediaInfo?.contents ?? [])) {
            item.mediaStatus?.hasPaid = true;
          }
          for (ComicChapterInfo item in (videoModel?.mediaInfo?.episodeList ?? [])) {
            item.hasBuy = true;
          }
        }
        globalStore.refreshWallet();
        Navigator.pop(context, true);
      } else {
        if (data.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast("网络异常, 支付失败");
        }
      }
    } on DioException catch (e) {
      LoadingAlertWidget.cancel();
      var error = e.error;
      if (error is ApiException) {
        if (error.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast(error.message);
        }
      } else {
        showToast(e.toString());
      }

      debugLog('productBuy', e.toString());
    } catch (e) {
      LoadingAlertWidget.cancel();
      debugLog('postBuyVideo', e.toString());
    }
    isBuying = false;
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Material(
        color: Colors.transparent,
        child: Container(
          padding: const EdgeInsets.fromLTRB(16, 18, 16, 30),
          margin: const EdgeInsets.symmetric(horizontal: 42),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(18),
            gradient: const LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color(0xff141414),
                Colors.black,
              ],
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              const Text(
                "温馨提示",
                style: TextStyle(
                  fontSize: 20,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
              18.sizeBoxH,
              Container(
                height: 1,
                color: Colors.white.withOpacity(0.05),
              ),
              18.sizeBoxH,
              Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    "coin.webp".commonImgPath,
                    width: 24,
                    height: 24,
                  ),
                  15.sizeBoxW,
                  Text(
                    priceTitle,
                    style: const TextStyle(
                      fontSize: 16,
                      color: Colors.white,
                    ),
                  ),
                ],
              ),
              12.sizeBoxH,
              Text(
                "解锁即可查看精彩内容",
                style: const TextStyle(
                  fontSize: 14,
                  color: Colors.white,
                ),
              ),
              12.sizeBoxH,
              Text(
                "当前余额: ${globalStore.wallet?.amount}金币",
                style: const TextStyle(
                  fontSize: 16,
                  color: Colors.white,
                ),
              ),
              18.sizeBoxH,
              Container(
                height: 42,
                width: 244,
                child: InkWell(
                  onTap: () async {
                    _buyProduct(false);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      color: Color(0xffFF004F),
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child: Text(
                      "立即解锁",
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
